//
//  EMMAlertViewController.m
//  EMMApp
//
//  Created by Mac on 16/5/5.
//  Copyright © 2016年 YiXun. All rights reserved.
//

#import "EMMAlertViewController.h"

#define OnePixel     (1./[UIScreen mainScreen].scale)
#define animateTime  0.35f
#define UIColorFromHEX(hexValue, alphaValue) \
        [UIColor colorWithRed:((float)((hexValue & 0xFF0000) >> 16))/255.0 \
        green:((float)((hexValue & 0x00FF00) >> 8))/255.0 \
        blue:((float)(hexValue & 0x0000FF))/255.0 \
        alpha:alphaValue]

@interface EMMAlertViewController () {
    NSString *nameTitle;
    NSString *confirmString;
    NSString *cancelString;
}


@property (nonatomic, assign) BOOL notifiKeyboardHide;

@property (nonatomic, strong) UITextView * inputTextView;  //输入框
@property (nonatomic, strong) UIView * operateView; //操作视图

@property (nonatomic, strong) UIButton * reloadImageBtn;

@property (nonatomic, copy) ClickBlock confirmBlock;
@property (nonatomic, copy) CancelBlock cancelBlock;

@end

@implementation EMMAlertViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = UIColorFromHEX(0x000000, 0.5);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    //必须在这里，否则动画无效
    [self showAlertView];
}

- (instancetype)initWithtitile:(NSString *)title confirmTitle:(NSString *)confirmTitle cancelTitle:(NSString *)cancelTitle confirmAction:(ClickBlock)confirmBlock andCancelAction:(CancelBlock)cancelBlcok
{
    if (self = [super init]) {
        self.confirmBlock = confirmBlock;
        self.cancelBlock = cancelBlcok;
        nameTitle = title;
        confirmString = confirmTitle;
        cancelString = cancelTitle;
        
        self.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
        self.modalPresentationStyle = UIModalPresentationOverFullScreen;
    }
    return self;
}


#pragma mark - 创建UI
- (void)showAlertView {
    _notifiKeyboardHide = NO;
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    /**
     *  操作区背景
     */
    _operateView = [[UIView alloc] init];
    _operateView.center = CGPointMake(EMM_WIDTH/2., EMM_HEIGHT/2.);
    _operateView.bounds = CGRectMake(0, 0, EMM_WIDTH - 40, 235);
    _operateView.backgroundColor = [UIColor colorFromHexCode:@"#f5f5f5"];
    _operateView.layer.cornerRadius = 6;
    _operateView.clipsToBounds = YES;
    [self.view addSubview:_operateView];
    [self shakeToShow:_operateView];

    /**
     *  标题
     */
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, _operateView.frame.size.width, 40)];
    titleLabel.text = nameTitle;
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.backgroundColor = [UIColor colorFromHexCode:@"#ebebeb"];
    [_operateView addSubview:titleLabel];
    
    /**
     *  按钮
     */
    UIButton * cancelBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    cancelBtn.frame = CGRectMake(0, CGRectGetHeight(_operateView.frame) - 48, _operateView.frame.size.width/2., 48);
    [cancelBtn setTitle:cancelString forState:UIControlStateNormal];
    [cancelBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [cancelBtn addTarget:self action:@selector(cancelAction:) forControlEvents:UIControlEventTouchUpInside];
    cancelBtn.backgroundColor = [UIColor colorFromHexCode:@"#f5f5f5"];
    [_operateView addSubview:cancelBtn];

    
    UIButton * confirmBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    confirmBtn.frame = CGRectMake(_operateView.frame.size.width/2., CGRectGetHeight(_operateView.frame) - 48, _operateView.frame.size.width/2., 48);
    [confirmBtn setTitle:confirmString forState:UIControlStateNormal];
    [confirmBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [confirmBtn addTarget:self action:@selector(confirmAction:) forControlEvents:UIControlEventTouchUpInside];
    [confirmBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    confirmBtn.backgroundColor = [UIColor colorFromHexCode:@"#ff7200"];
    [_operateView addSubview:confirmBtn];

    
    /**
     *  分割线
     */
    UILabel * horLine = [[UILabel alloc] initWithFrame:CGRectMake(0, CGRectGetHeight(_operateView.frame) - 48 - OnePixel, _operateView.frame.size.width, OnePixel)];
    horLine.backgroundColor = UIColorFromHEX(0xcccccc, 1);
    [_operateView addSubview:horLine];
    UILabel * verLine = [[UILabel alloc] initWithFrame:CGRectMake(_operateView.frame.size.width/2. - OnePixel/2., CGRectGetHeight(_operateView.frame) - 48 - OnePixel, OnePixel, 48)];
    verLine.backgroundColor = UIColorFromHEX(0xcccccc, 1);
    [_operateView addSubview:verLine];
    
    /**
     *  输入框
     */
   
    _inputTextView = [[UITextView alloc] initWithFrame:CGRectMake(15, titleLabel.frame.size.height+15, _operateView.frame.size.width-30, 115)];
    _inputTextView.layer.masksToBounds = YES;
    _inputTextView.layer.cornerRadius = 5;
    _inputTextView.delegate = self;
    _inputTextView.keyboardType = UIKeyboardTypeDefault;
    _inputTextView.returnKeyType = UIReturnKeyDone;
    _inputTextView.font = [UIFont systemFontOfSize:16];
    _inputTextView.layer.borderWidth = 1;
    _inputTextView.layer.borderColor = [[UIColor colorFromHexCode:@"#ff7200"] CGColor];
    [_operateView addSubview:_inputTextView];
    [_inputTextView becomeFirstResponder];
}

#pragma mark - 移除视图
- (void)removeAlertView
{
    if ([_inputTextView isFirstResponder]) {
        [_inputTextView resignFirstResponder];
    }
    
    [UIView animateWithDuration:0.15 animations:^{
        _operateView.alpha = 0;
        _operateView.transform = CGAffineTransformMakeScale(0.1, 0.1);
    } completion:^(BOOL finished) {
        [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
        if (_notifiKeyboardHide) {
            [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
        }
        
        [self dismissViewControllerAnimated:YES completion:nil];
    }];
}

- (void)confirmAction:(UIButton *)sender
{
    if (self.confirmBlock) {
        self.confirmBlock(_inputTextView.text);
    }
    
    [self removeAlertView];
}
- (void)cancelAction:(UIButton *)sender
{
    if (self.cancelBlock) {
        self.cancelBlock();
    }
    
    [self removeAlertView];
}

#pragma mark - 监听键盘弹起，操作框动画
///键盘弹起，页面动画，监听
- (void)keyboardWillShow:(NSNotification *)notification
{
    // 键盘的frame
    CGRect keyboardRect = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat keyboardHeight = keyboardRect.size.height;
    
    CGFloat keyboardOriginY = EMM_HEIGHT - keyboardHeight;
    CGFloat operateMaxY = EMM_HEIGHT/2. + _operateView.bounds.size.height/2. + 16;
    //    DLog(@"--- %lf %lf", keyboardOriginY, operateMaxY);
    
    if (operateMaxY >= keyboardOriginY) {
        [UIView animateWithDuration:0.25 animations:^{
            CGRect rect = _operateView.frame;
            rect.origin.y = keyboardOriginY - rect.size.height - 16;
            _operateView.frame = rect;
        } completion:^(BOOL finished) {
            
        }];
        _notifiKeyboardHide = YES;
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(keyboardWillHide:)
                                                     name:UIKeyboardWillHideNotification
                                                   object:nil];
    }
    else {
        _notifiKeyboardHide = NO;
    }
}
///键盘收起，页面动画，监听
- (void)keyboardWillHide:(NSNotification *)notification
{
    [UIView animateWithDuration:0.25 animations:^{
        CGRect rect = _operateView.frame;
        rect.origin.y = (EMM_HEIGHT - rect.size.height)/2.;
        _operateView.frame = rect;
    } completion:^(BOOL finished) {
        
    }];
}

-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if ([text isEqualToString:@"\n"]) {
        [_inputTextView resignFirstResponder];
        return NO;
    }
    return YES;
}

#pragma mark - 弹性震颤动画
- (void)shakeToShow:(UIView *)aView
{
    CAKeyframeAnimation * popAnimation = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
    popAnimation.duration = 0.35;
    popAnimation.values = @[[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.01f, 0.01f, 1.0f)],
                            [NSValue valueWithCATransform3D:CATransform3DMakeScale(1.05f, 1.05f, 1.0f)],
                            [NSValue valueWithCATransform3D:CATransform3DMakeScale(0.9f, 0.9f, 1.0f)],
                            [NSValue valueWithCATransform3D:CATransform3DIdentity]];
    popAnimation.keyTimes = @[@0.0f, @0.5f, @0.75f, @0.8f];
    popAnimation.timingFunctions = @[[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut],
                                     [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut],
                                     [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
    [aView.layer addAnimation:popAnimation forKey:nil];
}

@end
